﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Aliyeye.Car.Net.UI.PopupDialog;
using Aliyeye.Car.Net.Utility;
using Aliyeye.Car.Net.UI.Common;
using System.IO;

namespace Aliyeye.Car.Net.UI.AccountsUsersModel
{
    public partial class AddUsers : Aliyeye.Car.Net.UI.BaseForm
    {
        public Aliyeye.Car.Net.UI.AccountsUsersSvc.SoapHeaderClass sopaHeader = new Aliyeye.Car.Net.UI.AccountsUsersSvc.SoapHeaderClass();

        private bool isDriver = false;
        private int userID = 0;
        //private bool isexistusername = false;
        private string userName = "";

        public AddUsers()
        {
            InitializeComponent();
        }

        public AddUsers(bool isDri)
        {
            InitializeComponent();
            isDriver = isDri;
            if (isDri)
            {
                this.Text = "添加驾驶员信息";
                groupBox1.Text = "驾驶员信息";
            }
            else
            {
                this.Text = "添加账号信息";
                groupBox1.Text = "账号信息";
            }
        }

        public AddUsers(bool isDri, int id)
        {
            InitializeComponent();
            isDriver = isDri;
            userID = id;
            if (isDri)
            {
                this.Text = "修改驾驶员信息";
                groupBox1.Text = "驾驶员信息";
            }
            else
            {
                this.Text = "修改账号信息";
                groupBox1.Text = "账号信息";
            }
        }

        private void BindInfo()
        {
            overlay.FadeIn();Cursor.Current = Cursors.WaitCursor;
            Cursor.Current = Cursors.WaitCursor;
            //if (userID != 0)
            //{
            //    txtPassword.Visible = false;
            //    label15.Visible = false;
            //}

            AccountsUsersSvc.Accounts_Users model = new Aliyeye.Car.Net.UI.AccountsUsersSvc.Accounts_Users();
            ServiceManipulator.SafeAsyncExecution<AccountsUsersSvc.Accounts_UsersServiceSoapClient>(
                proxy => proxy.GetModel(sopaHeader, userID),
                result =>
                {
                    if (result.Error == null)
                    {
                        model = (AccountsUsersSvc.Accounts_Users)result.Result;
                        if (model != null)
                        {
                            txtAddr.Text = model.Addr;
                            txtEmail.Text = model.Email;
                            txtHomeTel.Text = model.HomeTel;
                            //txtPassword.Text = model.Password.ToString();
                            txtQQ.Text = model.QQ;
                            txtSchool.Text = model.School;
                            txtTel.Text = model.Tel;
                            txtTrueName.Text = model.TrueName;
                            txtUserName.Text = model.UserName;
                            userName = model.UserName;
                            cbbDepart.SelectedValue = model.DepID;
                            cbbRole.SelectedValue = model.RoleId;
                            cbbSex.Text = model.Sex;
                            dtpBirth.Value = Convert.ToDateTime(model.Birth);
                            dtpDriveTime.Value = model.DriveTime;
                            dtpInputTime.Value = model.InputTime;
                            cmbCarType.Text = model.CarType;
                            if (model.UserImage != null)
                            {
                                pictureBoxUser.Image = byteToBitmap(model.UserImage);
                                byteUser = model.UserImage;
                            }
                            if (model.DriverImage != null)
                            {
                                pictureBoxDriver.Image = byteToBitmap(model.DriverImage);
                                byteDriver = model.DriverImage;
                            }
                        }
                        overlay.FadeOut();Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut();Cursor.Current = Cursors.Default;
                    }
                },
                this
            );
        }

        public Bitmap byteToBitmap(byte[] imageBytes)
        {
            if (imageBytes.Length == 0 || imageBytes.Length < 0)
            {
                return null;
            }

            string imageType = Encoding.ASCII.GetString(imageBytes, 20, 12);
            MemoryStream stream;
            if (imageType == "Bitmap Image")
            {
                //如果数据库中保存的是BMP图形则需要去掉OLE头
                stream = new MemoryStream(imageBytes, 78, imageBytes.Length - 78);
            }
            else
            {
                stream = new MemoryStream(imageBytes, 0, imageBytes.Length);
            }

            Bitmap bmp = new Bitmap(stream);

            return bmp;
        }

        private void AddUsers_Load(object sender, EventArgs e)
        {
            BindComboBoxInfo();
            if (userID != 0)
                BindInfo();
        }

        private void BindComboBoxInfo()
        {
            cbbSex.SelectedIndex = 0;
            overlay.FadeIn();Cursor.Current = Cursors.WaitCursor;
            Cursor.Current = Cursors.WaitCursor;
            Accounts_RolesSvc.SoapHeaderClass sopaHeaderRole = new Accounts_RolesSvc.SoapHeaderClass();
            Base_DepartmentSvc.SoapHeaderClass sopaHeaderDepart = new Base_DepartmentSvc.SoapHeaderClass();

            string strWhere = string.Empty;
            DataSet dtRole = null;

            if (isDriver)
            {
                strWhere = "Description ='驾驶员'";
                cbbRole.Enabled = false;
                cbbRole.SelectedText = "驾驶员";

            }
            else
            {
                strWhere = "Description !='驾驶员'";
                pictureBoxDriver.Visible = false;
                label17.Visible = false;
                //label17.Visible = false;
                //label18.Visible = false;
                //label19.Visible = false;
                //label20.Visible = false;
                //label21.Visible = false;
                //label23.Visible = false;
                label24.Visible = false;
                //label25.Visible = false;

                dtpDriveTime.Visible = false;
                cmbCarType.Visible = false;
                label32.Visible = false;
                label13.Visible = false;
            }

            ServiceManipulator.SafeAsyncExecution<Accounts_RolesSvc.Accounts_RolesServiceSoapClient>(
                proxy => proxy.GetList(sopaHeaderRole, strWhere),
                result =>
                {
                    if (result.Error == null)
                    {
                        dtRole = (DataSet)result.Result;
                        cbbRole.DisplayMember = "Description";
                        cbbRole.ValueMember = "RoleID";
                        cbbRole.DataSource = dtRole.Tables[0];
                        cbbRole.SelectedIndex = 0;

                        overlay.FadeOut();Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut();Cursor.Current = Cursors.Default;
                    }
                },
                this
            );

            DataSet dtDepart = null;
            ServiceManipulator.SafeAsyncExecution<Base_DepartmentSvc.Base_DepartmentServiceSoapClient>(
                proxy => proxy.GetList(sopaHeaderDepart, ""),
                result =>
                {
                    if (result.Error == null)
                    {
                        dtDepart = (DataSet)result.Result;
                        cbbDepart.DisplayMember = "ClassName";
                        cbbDepart.ValueMember = "ClassID";
                        cbbDepart.DataSource = dtDepart.Tables[0];
                        cbbDepart.SelectedIndex = 0;

                        overlay.FadeOut();Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut();Cursor.Current = Cursors.Default;
                    }
                },
                this
            );

            ArchivesSvc.SoapHeaderClass sopaHeader = new ArchivesSvc.SoapHeaderClass();

            DataSet ds = null;

            ServiceManipulator.SafeAsyncExecution<ArchivesSvc.ArchivesServiceSoapClient>(
                proxy => proxy.ComBoxCarX(sopaHeader),
                result =>
                {
                    if (result.Error == null)
                    {
                        ds = (DataSet)result.Result;

                        cmbCarType.DisplayMember = "Namevalue";
                        cmbCarType.ValueMember = "Id";
                        cmbCarType.DataSource = ds.Tables[0];
                        cmbCarType.SelectedIndex = 0;

                        overlay.FadeOut();Cursor.Current = Cursors.Default;
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut();Cursor.Current = Cursors.Default;
                    }
                },
                this
            );
        }

        //保存
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtUserName.Text))
            {
                DialogWarning dia = new DialogWarning("登录用户名不能为空！");
                dia.ShowDialog();
                return;
            }

            if (string.IsNullOrEmpty(txtTrueName.Text))
            {
                DialogWarning dia = new DialogWarning("真实姓名不能为空！");
                dia.ShowDialog();
                return;
            }
            if (string.IsNullOrEmpty(dtpBirth.Text))
            {
                DialogWarning dia = new DialogWarning("出生年月不能为空！");
                dia.ShowDialog();
                return;
            }

            if (string.IsNullOrEmpty(txtTel.Text))
            {
                DialogWarning dia = new DialogWarning("手机不能为空！");
                dia.ShowDialog();
                return;
            }

            if (string.IsNullOrEmpty(txtEmail.Text))
            {
                DialogWarning dia = new DialogWarning("Email不能为空！");
                dia.ShowDialog();
                return;
            }
            if (string.IsNullOrEmpty(txtHomeTel.Text))
            {
                DialogWarning dia = new DialogWarning("老家电话不能为空！");
                dia.ShowDialog();
                return;
            }

            if (string.IsNullOrEmpty(txtPassword.Text))
            {
                DialogWarning dia = new DialogWarning("密码不能为空！");
                dia.ShowDialog();
                return;
            }

            if (isDriver)
            {
                if (string.IsNullOrEmpty(dtpDriveTime.Text))
                {
                    DialogWarning dia = new DialogWarning("驾驶员到期不能为空！");
                    dia.ShowDialog();
                    return;
                }
            }


            //判断是否已经存在登入用户名
            if (txtUserNameisexist(txtUserName.Text.ToString().Trim()))
            {
                PageCommon.Notify("登录用户名已存在！");
                return;
            }

            overlay.FadeIn();Cursor.Current = Cursors.WaitCursor;
            Cursor.Current = Cursors.WaitCursor;

            AccountsUsersSvc.Accounts_Users info = new Aliyeye.Car.Net.UI.AccountsUsersSvc.Accounts_Users();


            //Model.Accounts_Users info = new Model.Accounts_Users();
            info.UserName = txtUserName.Text;
            info.Password = JhEncrypt.EncryptPassword(txtPassword.Text);
            info.TrueName = txtTrueName.Text;
            info.DepID = Convert.ToInt32(cbbDepart.SelectedValue);
            info.Sex = cbbSex.Text;
            info.Birth = dtpBirth.Value.ToString("yyyy-MM-dd");
            info.Addr = txtAddr.Text;
            info.Tel = txtTel.Text;
            info.Email = txtEmail.Text;
            info.QQ = txtQQ.Text;
            info.School = txtSchool.Text;
            info.InputTime = dtpInputTime.Value;
            info.DriveTime = dtpDriveTime.Value;
            info.HomeTel = txtHomeTel.Text;
            info.State = true;
            info.RoleId = Convert.ToInt32(cbbRole.SelectedValue);
            info.CarType = cmbCarType.Text;
            if (mStreamUser != null && isUpdateForUser)
                info.UserImage = mStreamUser.GetBuffer();  //添加，更新时改了图片
            else if (mStreamUser == null && !isUpdateForUser)
                info.UserImage = byteUser;   // 更新时没改图片
            else
                info.UserImage = new byte[0];

            if (mStreamDriver != null && isUpdateForDriver)
                info.DriverImage = mStreamDriver.GetBuffer();
            else if (mStreamDriver == null && !isUpdateForDriver)
                info.DriverImage = byteDriver;
            else
                info.DriverImage = new byte[0];

            //BLL.Accounts_Users bll = new BLL.Accounts_Users();

            if (userID == 0)
            {
                //添加
                ServiceManipulator.SafeAsyncExecution<AccountsUsersSvc.Accounts_UsersServiceSoapClient>(
                    proxy => proxy.Add(sopaHeader, info),
                    result =>
                    {
                        if (result.Error == null)
                        {
                            if (isDriver)
                            {
                                PageCommon.Notify("添加驾驶员信息成功！");
                            }
                            else
                            {
                                PageCommon.Notify("添加账号信息成功！");
                            }


                            overlay.FadeOut();Cursor.Current = Cursors.Default;
                            ClearControlText();
                        }
                        else
                        {
                            PageCommon.Error(result.Error.Message); overlay.FadeOut();Cursor.Current = Cursors.Default;
                        }
                    },
                    this
                );
                //bll.Add(info);
                //DialogNotify diaSecc = new DialogNotify("添加账号信息成功！");
                //diaSecc.ShowDialog();
            }
            else
            {
                //修改
                info.UserID = userID;
                ServiceManipulator.SafeAsyncExecution<AccountsUsersSvc.Accounts_UsersServiceSoapClient>(
                proxy => proxy.Update(sopaHeader, info),
                result =>
                {
                    if (result.Error == null)
                    {
                        if (isDriver)
                        {
                            PageCommon.Notify("修改驾驶员信息成功！");
                        }
                        else
                        {
                            PageCommon.Notify("修改账号信息成功！");
                        }
                        overlay.FadeOut();Cursor.Current = Cursors.Default;
                        this.Close();
                    }
                    else
                    {
                        PageCommon.Error(result.Error.Message); overlay.FadeOut();Cursor.Current = Cursors.Default;
                    }
                },
                this
            );
                //bll.Update(info);
                //DialogNotify diaSecc = new DialogNotify("修改账号信息成功！");
                //diaSecc.ShowDialog();
            }
        }

        private void ClearControlText()
        {
            txtAddr.Text = string.Empty;
            txtEmail.Text = string.Empty;
            txtHomeTel.Text = string.Empty;
            txtPassword.Text = string.Empty;
            txtQQ.Text = string.Empty;
            txtSchool.Text = string.Empty;
            txtTel.Text = string.Empty;
            txtTrueName.Text = string.Empty;
            txtUserName.Text = string.Empty;
            cbbDepart.SelectedIndex = 0;
            cbbRole.SelectedIndex = 0;
            cbbSex.SelectedIndex = 0;
            dtpBirth.Value = DateTime.Now;
            dtpDriveTime.Value = DateTime.Now;
            dtpInputTime.Value = DateTime.Now;
            pictureBoxDriver.Image = null;
            pictureBoxUser.Image = null;
            mStreamDriver = null;
            mStreamUser = null;
            byteUser = new byte[0];
            byteDriver = new byte[0];
            cmbCarType.SelectedIndex = 0;
        }

        //取消
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        public bool txtUserNameisexist(string txtUserName)
        {
            if (txtUserName.Trim() == userName)
            {
                return false;
            }

            AccountsUsersSvc.Accounts_UsersServiceSoapClient client = new Aliyeye.Car.Net.UI.AccountsUsersSvc.Accounts_UsersServiceSoapClient();
            bool result = client.IsExistUserName(sopaHeader, txtUserName);
            return result;

            //overlay.FadeIn();Cursor.Current = Cursors.WaitCursor;

            //ServiceManipulator.SafeAsyncExecution<AccountsUsersSvc.Accounts_UsersServiceSoapClient>(
            //        proxy => proxy.IsExistUserName(sopaHeader, txtUserName),
            //        result =>
            //        {
            //            if (result.Error == null)
            //            {
            //                {
            //                    bool isexist = (bool)result.Result;
            //                    if (isexist == true)
            //                    {
            //                        isexistusername =  isexist;
            //                        overlay.FadeOut();Cursor.Current = Cursors.Default;

            //                    }
            //                }
            //            }
            //            else
            //            {
            //                PageCommon.Error(result.Error.Message); overlay.FadeOut();Cursor.Current = Cursors.Default;
            //            }
            //        },
            //        this
            //    );
        }

        private string picPathUser = "";
        private string picPathDriver = "";
        MemoryStream mStreamUser = null;
        MemoryStream mStreamDriver = null;
        byte[] byteUser = new byte[0];
        byte[] byteDriver = new byte[0];
        bool isUpdateForUser = false;
        bool isUpdateForDriver = false;

        private void pictureBoxUser_Click(object sender, EventArgs e)
        {
            if (this.openFileDialogUser.ShowDialog() == DialogResult.OK)
            {
                if (this.openFileDialogUser.FileName.Trim() != "")
                {
                    picPathUser = this.openFileDialogUser.FileName;
                }
                FileStream imageStream = new FileStream(picPathUser, FileMode.Open);
                mStreamUser = new MemoryStream();
                byte[] imageData = new byte[1024];
                int count = 0;
                while (0 < (count = imageStream.Read(imageData, 0, imageData.Length)))
                {
                    mStreamUser.Write(imageData, 0, count);
                }
                isUpdateForUser = true;
                Image image = Image.FromStream(imageStream, false);
                if (image.Width > 160 || image.Height > 170)
                {
                    mStreamUser = null;
                    picPathUser = "";
                    PageCommon.Alert("图片规格太大，请上传小于160*170规格的图片");
                    return;
                }
                else
                {
                    pictureBoxUser.Image = image;
                }
                imageStream.Close();
            }
        }

        private void pictureBoxDriver_Click(object sender, EventArgs e)
        {
            if (this.openFileDialogDriver.ShowDialog() == DialogResult.OK)
            {
                if (this.openFileDialogDriver.FileName.Trim() != "")
                {
                    picPathDriver = this.openFileDialogDriver.FileName;
                }
                FileStream imageStream = new FileStream(picPathDriver, FileMode.Open);
                mStreamDriver = new MemoryStream();
                byte[] imageData = new byte[1024];
                int count = 0;
                while (0 < (count = imageStream.Read(imageData, 0, imageData.Length)))
                {
                    mStreamDriver.Write(imageData, 0, count);
                }
                isUpdateForDriver = true;
                Image image = Image.FromStream(imageStream, false);
                if (image.Width > 160 || image.Height > 170)
                {
                    mStreamDriver = null;
                    picPathDriver = "";
                    PageCommon.Alert("图片规格太大，请上传小于160*170规格的图片");
                    return;
                }
                else
                {
                    pictureBoxDriver.Image = image;
                }
                imageStream.Close();
            }
        }

        private void label16_Click(object sender, EventArgs e)
        {

        }


    }
}
